package com.xzlf.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.scheduling.config.Task;
import org.springframework.scheduling.support.ScheduledMethodRunnable;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

//@Component
public class SchedulerServiceImpl {
    // 得到BeanPostProcessor
//    @Autowired
    private ScheduledAnnotationBeanPostProcessor postProcessor;

    public void restartAllTasks() {
        // 拿到所有的task(带包装)
        Set<ScheduledTask> tasks = postProcessor.getScheduledTasks();
        Set<Object> rawTasks = new HashSet<>(tasks.size());
        for (ScheduledTask task : tasks) {
            Task t = task.getTask();

            ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) t.getRunnable();
            Object taskObject = runnable.getTarget();
            // 将task所关联的对象放到Set中(就是带@Scheduled方法的类)
            rawTasks.add(taskObject);
        }

        // 调用postProcessBeforeDestruction()方法，将task移除并cancel
        for (Object obj : rawTasks) {
            postProcessor.postProcessBeforeDestruction(obj, "scheduledTasks");
        }

        // 调用postProcessAfterInitialization()方法重新schedule task
        for (Object obj : rawTasks) {
            postProcessor.postProcessAfterInitialization(obj, "scheduledTasks");
        }
    }
}
